package cz.cvut.fit.mi_paa.sat;

import cz.cvut.fit.mi_paa.abs.Context;
import cz.cvut.fit.mi_paa.abs.Instance;
import cz.cvut.fit.mi_paa.knapsack.Item;
import cz.cvut.fit.mi_paa.knapsack.KnapsackInstance;
import cz.cvut.fit.mi_paa.utils.StopWatch;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: milos
 * Date: 27.1.13
 * Time: 22:27
 * To change this template use File | Settings | File Templates.
 */
public class SatContext extends Context {

    private SatInstance instance;

    public SatContext(FileWriter resultWriter, BufferedReader inputReader, StopWatch sw) {
        super(resultWriter, inputReader, sw);
    }

    @Override
    public boolean nextInstance() throws IOException {
        String instanceIdString = inputReader.readLine();
        if(instanceIdString!=null) {
            this.instance = new SatInstance();
            String[] lineElements = instanceIdString.split("\\s");
            instance.setId(lineElements[1]);
        } else {
            return false;
        }

        String line;
        List<Term> termList=null;
        int[] weights=null;
        while ((line=inputReader.readLine())!=null) {
            String[] lineElements = line.split("\\s");
            if(lineElements[0].equals("c")) continue;
            if(lineElements[0].equals("p")) {
                instance.setVariableNum(Integer.valueOf(lineElements[2]));
                termList = new ArrayList<Term>();
                weights = new int[Integer.valueOf(lineElements[2])];
            } else if(lineElements[0].equals("s")) {
                instance.setBestWeight(Integer.valueOf(lineElements[1]));
            } else if(lineElements[0].equals("w")) {
                for (int i = 1;i<lineElements.length;i++) {
                    weights[i-1] = Integer.valueOf(lineElements[i]);
                }
            }
            else if(lineElements[0].equals("%")) {
                break;
            } else {
                Term term = new Term();
                for (String lineElement : lineElements) {
                    if(!lineElement.equals("0")) {
                        term.addVariable(Integer.valueOf(lineElement));
                    } else {
                        break;
                    }
                }
                termList.add(term);
            }
        }
        instance.setTerms(termList);
        instance.setWeights(weights);
        return false;
    }

    @Override
    public void close() throws IOException {
        resultWriter.close();
        inputReader.close();
    }

    @Override
    public Instance getInstance() {
        return instance;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
